<?php

namespace common\models\bill;

use Yii;

/**
 * This is the model class for table "{{%bill}}".
 *
 * @property int $id
 * @property string $bill_no 票据编号
 * @property int $type_id 类型ID
 * @property int $company_id 公司单位ID
 * @property int $user_id 用户ID
 * @property int $nums 标签数
 * @property string $token 校验令牌
 * @property int $status 状态
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 * @property int $deleted_at 删除时间
 */
class Bill extends \common\db\ActiveRecord {

    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%bill}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['bill_no'], 'required'],
            [['type_id', 'company_id', 'user_id', 'nums', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['bill_no'], 'string', 'max' => 32],
            [['token'], 'string', 'max' => 255],
            [['token'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'bill_no' => '票据编号',
            'type_id' => '类型ID',
            'company_id' => '公司单位ID',
            'user_id' => '操作员ID',
            'nums' => '标签数',
            'token' => '校验令牌',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];
    }

    public function getData() {
        return $this->hasMany(BillData::className(), ['bill_id' => 'id']);
    }

    public function getRfids() {
        return $this->hasMany(\common\models\rfid\Rfid::className(), ['bill_id' => 'id']);
    }
    
    public function getLogs() {
        return $this->hasMany(\common\models\inventory\InventoryLog::className(), ['bill_id' => 'id']);
    }

    public function getRoutes() {
        return $this->hasMany(BillTypeRoute::className(), ['type_id' => 'type_id'])->orderBy([
            'level' => SORT_ASC,
        ]);
    }

    public function isBetween($data, $range) {
        $min = min($range);
        $max = max($range);
        if ($data >= $min && $data <= $max) {
            return true;
        }
        return false;
    }

    public function getRoute() {
        $data = [];
        $routes = $this->routes;
        foreach ($routes as $route) {
            if ($route->level) {
                $checkData = false;
                if ($route->node_type == 1) {
                    $checkData = $this->created_at;
                } elseif ($route->node_type == 2) {
                    $checkData = $this->bill_no;
                }
                if ($this->isBetween($checkData, [$route->segment_begin, $route->segment_end])) {
                    //一级路由
                    $data[$route->level] = $route->route;
                }
            } else {
                //一级路由
                $data[$route->level] = $route->route;
            }
        }
        return implode('-', $data);
    }

    /**
     * 获取账号密码重置token
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByToken($token) {
        if (!static::isBuildTokenValid($token)) {
            return null;
        }
        return static::findOne([
            'token' => $token,
            'status' => self::STATUS_DEFAULT,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function validateBuildToken() {
        return $this->token === $token && static::isBuildTokenValid($token);
    }

    /**
     * @inheritdoc
     */
    public function refreshBuildToken() {
        if (!static::isBuildTokenValid($this->token)) {
            $this->generateBuildToken();
            if (!$this->save()) {
                return $this->dumpError('Token刷新失败');
            }
        }
        return $this->toArray();
    }

    /**
     * 生成密码重置token
     */
    public function generateBuildToken() {
        $this->token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * 移除密码重置token
     */
    public function removeBuildToken() {
        $this->token = null;
    }

    /**
     * 判断用户密码重置token是否有效
     * @param string $token password reset token
     * @return bool
     */
    public static function isBuildTokenValid($token) {
        if (empty($token)) {
            return false;
        }
        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = 1800;
        return $timestamp + $expire >= time();
    }

    public function setActived() {
        $this->removeBuildToken();
        $this->status = self::STATUS_ACTIVE;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        return [
            'token',
            'rfids',
        ];
    }

}
